﻿using System;
using System.Linq;
using DataAccess.Accessors.Interfaces;
using DataAccess.DAO;
using NHibernate.Linq;

namespace DataAccess.Accessors
{
    public class SecurityKeyAccessor : ISecurityKeyAccessor
    {
        private readonly IDataAccessor _dataAccessor;

        public SecurityKeyAccessor(IDataAccessor dataAccessor)
        {
            _dataAccessor = dataAccessor;
        }

        public SecurityKeyDAO GetSecurityKeyDAO(string securityKey)
        {
            using (var session = _dataAccessor.OpenNHibernateSession())
            {
                return (from securityKeyDao in session.Query<SecurityKeyDAO>()
                        where securityKeyDao.SecurityKey == securityKey
                        select securityKeyDao).SingleOrDefault();
            }
        }

        public void SaveSecurityKeyForUser(long userId, string securityKey)
        {
            using (var session = _dataAccessor.OpenNHibernateSession())
            {
                var securityKeyDao = new SecurityKeyDAO(userId, securityKey);
                using (var transaction = session.BeginTransaction())
                {
                    session.SaveOrUpdate(securityKeyDao);
                    transaction.Commit();
                }
            }
        }

        public void RemoveSecurityKeyForUser(long userId, string securityKey)
        {
            using (var session = _dataAccessor.OpenNHibernateSession())
            {
                var securityKeyDao = new SecurityKeyDAO(userId, securityKey);
                using (var transaction = session.BeginTransaction())
                {
                    session.Delete(securityKeyDao);
                    transaction.Commit();
                }
            }
        }
    }
}
